package com.neuedu.helloworld;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;


/**
 * com.neuedu.helloworld.R
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {


    public static final String AUTO_LOGIN = "login";

    private Button btnLogin;
    private TextView txtForgetPassword;
    private EditText etUserName;
    private EditText etPassword;
    private CheckBox ckRemember;












    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //R   android.R
        setContentView(R.layout.activity_login);

        //加载完布局文件，当前Activity可以获取到组件
        btnLogin = findViewById(R.id.btnLogin);
        txtForgetPassword = findViewById(R.id.txtForgetPassword);
        etUserName = findViewById(R.id.etUserName);
        etPassword = findViewById(R.id.etPassword);
        ckRemember = findViewById(R.id.ckRemember);


        txtForgetPassword.setText(Html.fromHtml("<a href=\"http://www.12306.cn/lostPassword\">忘记密码？</a>"));
        txtForgetPassword.setMovementMethod(LinkMovementMethod.getInstance());


        //设置事件监听对象
//        btnToMain.setOnClickListener(new BtnClickListener());
        btnLogin.setOnClickListener(this);

        System.out.println("日志日志日志日志日志1");


        Log.i("LoginActivity", "i一般信息");
        Log.v("LoginActivity", "v冗余");
        Log.w("LoginActivity", "w警告");
        Log.e("LoginActivity", "e错误异常的");

        Log.d("LoginActivity", " LoginActivity.onCreate ");

    }


    @Override
    protected void onStart() {
        super.onStart();
        Log.d("LoginActivity", ":  LoginActivity.onStart ");


    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d("LoginActivity", ":  LoginActivity.onResume ");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("LoginActivity", ":  LoginActivity.onPause ");


    }


    @Override
    protected void onStop() {
        super.onStop();
        Log.d("LoginActivity", ":  LoginActivity.onStop ");

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("LoginActivity", ":  LoginActivity.onDestroy ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("LoginActivity", ":  LoginActivity.onRestart ");
    }


    @Override
    public void onClick(View v) {
        //吐司
        //Toast.makeText(this, "按钮被点击.....", Toast.LENGTH_LONG).show();


        //访问  用户名、密码的文本框
        String userName = etUserName.getText().toString();
        String password = etPassword.getText().toString();


        if (userName == null || userName.trim().length() <= 0) {
            etUserName.requestFocus();
            etUserName.setError("请输入用户名");
            return;
        }

        if (password == null || password.trim().length() <= 0) {
            etPassword.requestFocus();
            etPassword.setError("请输入密码");
            return;
        }


//        new LoginTread(userName,password).start();

        //执行任务
         new LoginAsyncTask().execute(userName,password);



//        //登录成功的时候
//        if("admin".equals(userName) && "123456".equals(password)){
//
//
//            autoLogin();
//
//
//            //跳转到新 的activity
//            //显示意图
//            Intent intent = new Intent(this, MainActivity.class );
//
//            //通过意图启动Activity
//            startActivity(intent);
//
//            //结束当前的Activity 新画面 后退的时候看不到这个LoginActivity
//            finish();
//        }else{
//            etUserName.setError("用户名或者密码不对");
//        }


    }

    //判断是否自动登录， 如果勾选了，需要记录  username、password
    private void autoLogin() {
        if (ckRemember.isChecked()) {
            String userName = etUserName.getText().toString();
            String password = etPassword.getText().toString();


            //通过 SharedPreferences 记录用户名密码（token）

            //创建一个SharedPreferences 对象(xxx.xml)
            SharedPreferences sharedPreferences = getSharedPreferences(LoginActivity.AUTO_LOGIN, MODE_PRIVATE);


            //写入
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString("username", userName);
            edit.putString("password", password);


            //commit
            edit.commit();

        }


    }


    //定义监听器
//    class BtnClickListener implements  View.OnClickListener{
//
//        @Override
//        public void onClick(View v) {
//
//            Toast.makeText(LoginActivity.this, "按钮被点击.....", Toast.LENGTH_LONG).show();
//
//
//        }
//    }





    class LoginAsyncTask extends AsyncTask<String,Object,HashMap>{



        private ProgressDialog process  = null;
        /**
         *
         * @param params
         * @return
         */
        @Override
        protected HashMap doInBackground(String... params) {
            String username = params[0];
            String password = params[1];


            try {
                URL url = new URL("http://192.168.77.11:8080/login?username=" + username + "&password=" + password);
                URLConnection connection = url.openConnection();


                InputStream inputStream = connection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));


                Gson gson = new GsonBuilder().create();
                HashMap map = gson.fromJson(br, HashMap.class);


                return map;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        //预处理的任务
        @Override
        protected void onPreExecute() {

            //打开  loading

            //(Context context, CharSequence title,
            //            CharSequence message, boolean indeterminate,
            //            boolean cancelable, OnCancelListener cancelListener
            process = ProgressDialog.show(LoginActivity.this, "提示", "加载中，请稍后", false, false);

        }


        //请求响应回来的时候 执行
        //MainThread
        @Override
        protected void onPostExecute(HashMap result) {
            //关掉loading
            process.dismiss();


            if(result !=  null){
                Double  code = (Double) result.get("code");
//                Double  code = (Double) result.get("error");

                if(code.intValue() == 200){
                    String  token = (String) result.get("token");


                    //token  -- ShareadPreferences
                    //显示意图
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class );

                    //通过意图启动Activity
                    startActivity(intent);

                    //结束当前的Activity 新画面 后退的时候看不到这个LoginActivity
                    finish();
                }else{
                    Toast.makeText(LoginActivity.this, "登录失败了", Toast.LENGTH_SHORT).show();

                }

            }else{
                Toast.makeText(LoginActivity.this, "网络请求失败,请联系管理员", Toast.LENGTH_SHORT).show();
            }



        }
    }










}